/* 
 *  name: main.js
 *  author: akoyama
 *  description: Controls keyboard and mouse movement, which includes the UI buttons. 
 *  Creates gameField and calls functions on it.
 *  Creates an interval which automatically calls the 'falling' function. Handles start, pause, resume.
 */

// global variables
var GAME_SPEED = 1500;


//game keys
var ESC = 27;
var SPACE = 32;
var A = 65;
var W = 87;
var D = 68;
var S = 83;

$(document).ready(function() {
    
    //gameField controls the field, pills, and placed pills
    gameField = new GameField();
  
    $('body').keydown(keyPressedHandler);   
     
    //Game Control Buttons. 
    $('#startGame').click(function() {
        startGame();
    });
    
    $('#pauseGame').click(function () {
        pauseGame();
    });
    
    $('#resumeGame').click(function() {
        resumeGame();
    });
    
    $('#restartGame').click(function() {
         //start the pill at the top with the field cleared. no placed pills or viruses
         //not yet implemented
    });
    
    $('#endGame').click(function() {
         endGame();
    });
   
               
}); 

//Game Time Control Functions
function startGame() {
    //Currently, spamming startGame increases fallspeed. Also, if pressed quickly enough, will briefly spawn multiple pills.
   gameField.clearField();  //deletes whatever JS player just existed
   gameField.spawnPill();

   //Pill auto fall
   gameController = setInterval(pillFall, GAME_SPEED);
};

function pauseGame() {
    if(gameController)
        clearInterval(gameController);
        console.log('game paused!'); 
};

function resumeGame() {
    //Currently, pressing resumeGame if the game is not paused will cause a brief stall of the drop
    //However, using !(gameController) causes spamming the button to increase the speed of the fall
    clearInterval(gameController);
    gameController = setInterval(pillFall, GAME_SPEED);
    console.log('game resumed!');   
};

function endGame() {
    //game should not restart automatically using this
    if(gameController)
        clearInterval(gameController);
        console.log('clearInterval called on gameController!');
    gameField.clearField(); //deletes whatever JS player existed
};   

function pillFall() {
    gameField.movePill('down');
};

//Input Control
function keyPressedHandler(e) {
    //here for compat purposes across browsers
    var code = (e.keyCode ? e.keyCode : e.which);
	
    switch(code) {
        case A:
            gameField.movePill('left');
            break;
	case W:
            gameField.movePill('up');
            break;
        case D:
            gameField.movePill('right');
            break;
	case S:
            gameField.movePill('down');
            break;
	case SPACE:
            pauseGame();
            break;
	case ESC:
            endGame();
            break;
    }
}



   
 

    
    

